package com.lhl.booksystem.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.lhl.booksystem.pojo.Book;
import com.lhl.booksystem.service.BookService;
import com.lhl.booksystem.util.R;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author LHL
 */
@RestController
@RequestMapping("/book")
@CrossOrigin
public class BookController {
    @Resource
    private BookService bookService;

    @GetMapping("/books")
    public R all(){
        return new R(200,"查找成功!", true, this.bookService.findBook());
    }

    @PostMapping("/savebooks")
    public R add( Book book,@RequestParam MultipartFile head) throws IOException {
        String originalFilename = head.getOriginalFilename();
        String uuid = IdUtil.fastSimpleUUID();
        //路径
        String path = System.getProperty("book.dir")+"/src/main/resources/upload/"+uuid+"_"+originalFilename;
        FileUtil.writeBytes(head.getBytes(),path);
        //图片的处理
        String pic = Base64.encode(head.getBytes());
        book.setPhoto(pic);
        System.err.println(book.getBid());

        return  this.bookService.save(book)
                ?   new R(200,"成功",true)
                :  new R(201,"失败",false);
    }
    @GetMapping("/booktype")
    public R booktype(){
        return new R(200, "查找成功", true, this.bookService.findBookType());
    }


    @DeleteMapping("/delete/{ids}")
    public R delete(@PathVariable String ids){
        return  this.bookService.del(ids)
          ? new R(200, "删除成功", true)
          : new R(201, "删除失败", false);
    }
}
